package com.atguigu.chapter10;

import com.atguigu.bean.OrderEvent;
import com.atguigu.util.AnqclnUtil;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.cep.*;
import org.apache.flink.cep.nfa.aftermatch.AfterMatchSkipStrategy;
import org.apache.flink.cep.pattern.Pattern;
import org.apache.flink.cep.pattern.conditions.SimpleCondition;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.EventTimeSessionWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;

import java.time.Duration;
import java.util.List;
import java.util.Map;

/**
 * Author: Pepsi
 * Date: 2023/8/14
 * Desc:
 */


/*
*
* 用户恶意登录
*   这个案例对于恶意的定义是：2秒内连续登录失败就是恶意登录
*
* */


public class Flink08_Project_High_Order {
    public static void main(String[] args) {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 1000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(1);

        KeyedStream<OrderEvent, Long> stream = env
                .readTextFile("input/OrderLog.csv")
                .map(line -> {
                    String[] data = line.split(",");
                    return new OrderEvent(
                            Long.valueOf(data[0]),
                            data[1],
                            data[2],
                            Long.parseLong(data[3]) * 1000
                    );
                })
                // 分配时间戳和水印 ， 因为后面要用到窗口
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy
                                .<OrderEvent>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                                .withTimestampAssigner((log, ts) -> log.getEventTime())
                )
                // 以订单id分组
                .keyBy(OrderEvent::getOrderId);

        Pattern<OrderEvent, OrderEvent> pattern = Pattern
                .<OrderEvent>begin("create", AfterMatchSkipStrategy.skipPastLastEvent())
                .where(new SimpleCondition<OrderEvent>() {
                    @Override
                    public boolean filter(OrderEvent value) throws Exception {
                        return "create".equals(value.getEventType());
                    }
                }).optional()
                .next("pay")
                .where(new SimpleCondition<OrderEvent>() {
                    @Override
                    public boolean filter(OrderEvent value) throws Exception {
                        return "pay".equals(value.getEventType());
                    }
                })
                .within(Time.seconds(30));

        PatternStream<OrderEvent> ps = CEP.pattern(stream, pattern);

        /*SingleOutputStreamOperator<String> normal = ps
                .select(
                        new OutputTag<String>("timeout") {
                        },
                        new PatternTimeoutFunction<OrderEvent, String>() {
                            @Override
                            public String timeout(Map<String, List<OrderEvent>> pattern, long timeoutTimestamp) throws Exception {
                                return pattern.get("create").get(0).toString();
                            }
                        },
                        new PatternSelectFunction<OrderEvent, String>() {
                            @Override
                            public String select(Map<String, List<OrderEvent>> pattern) throws Exception {
                                return pattern.toString();
                            }
                        }
                );*/

        SingleOutputStreamOperator<OrderEvent> normal = ps.flatSelect(
                new OutputTag<OrderEvent>("timeout") {
                },
                new PatternFlatTimeoutFunction<OrderEvent, OrderEvent>() {
                    @Override
                    public void timeout(Map<String, List<OrderEvent>> pattern,
                                        long timeoutTimestamp,
                                        Collector<OrderEvent> out) throws Exception {
                        OrderEvent e = pattern.get("create").get(0);
                        out.collect(e);
                    }
                },
                new PatternFlatSelectFunction<OrderEvent, OrderEvent>() {
                    @Override
                    public void flatSelect(Map<String, List<OrderEvent>> pattern, Collector<OrderEvent> out) throws Exception {
                        if (!pattern.containsKey("create")) {
                            out.collect(pattern.get("pay").get(0));
                        }
                    }
                }
        );

        normal.print("normal");
        normal.getSideOutput(new OutputTag<OrderEvent>("timeout") {}).print("timeout");


        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
